package com.parleys.android.server.controller;

import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.parleys.android.server.util.ParleysServiceUtils;
import com.parleys.server.domain.News;
import com.parleys.server.domain.types.NewsType;
import com.parleys.server.dto.ChannelOverviewDTO;
import com.parleys.server.dto.OverviewResponseDTO;
import com.parleys.server.dto.SpaceOverviewDTO;
import com.parleys.server.frontend.service.ParleysService;

@Controller
@RequestMapping("/spaces")
public class SpacesController extends BaseController {

	@Autowired
	private ParleysService parleysService;

	@RequestMapping(method = RequestMethod.GET)
	public List<SpaceOverviewDTO> getSpaces() {
		OverviewResponseDTO<SpaceOverviewDTO> result = parleysService.getSpacesOverview(0, Integer.MAX_VALUE);
		for (Iterator<SpaceOverviewDTO> spaceIt = result.getOverviews().iterator(); spaceIt.hasNext(); ) {
			convertSpace(spaceIt.next());
		}
		return result.getOverviews();
	}

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public SpaceOverviewDTO getSpace(@PathVariable("id") long spaceId) {
        return convertSpace(parleysService.getSpaceOverviewDTO(spaceId));
    }
    
    @RequestMapping(value = "/{id}/news", method = RequestMethod.GET)
    public List<News> getNewsForSpace(@PathVariable("id") long spaceId) {
        return parleysService.getNews(NewsType.SPACE, spaceId, 0, Integer.MAX_VALUE).getOverviews();
    }

    @RequestMapping(value = "/{id}/news/start/{from}", method = RequestMethod.GET)
    public List<News> getNewsFromForSpace(@PathVariable("id") long spaceId,
    		@PathVariable("from") final long from) {
        List<News> result = this.getNewsForSpace(spaceId);
        ParleysServiceUtils.filterEntity(result, from);
        return result;
    }

    @RequestMapping(value = "/{id}/channels", method = RequestMethod.GET)
    public List<ChannelOverviewDTO> getChannelsForSpace(@PathVariable("id") long spaceId) {
        return parleysService.getChannelsOverview(spaceId).getOverviews();
    }

    private SpaceOverviewDTO convertSpace(SpaceOverviewDTO space) {
		space.setChannelIds(convertList(space.getChannelIds()));
		space.setStreamingServerIDs(convertList(space.getStreamingServerIDs()));
		return space;
    }

}
